package com.cskaoyan.service;

import com.cskaoyan.bean.MarketAd;
import com.cskaoyan.bean.MarketAdExample;
import com.cskaoyan.mapper.MarketAdMapper;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.StringUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

/**
 * @author Oarin
 * @class AdServiceImpl
 * @date 2023/6/1 10:41
 */
public class AdServiceImpl implements AdService {

    @Override
    public List<MarketAd> queryAdList(String name, String content, Integer page, Integer limit, String sort, String order) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        MarketAdExample example = new MarketAdExample();
        MarketAdExample.Criteria criteria = example.createCriteria();
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        if (content != null) {
            criteria.andContentLike("%" + content + "%");
        }
        PageHelper.startPage(page, limit);
        if (StringUtil.isNotEmpty(sort) && StringUtil.isNotEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        List<MarketAd> marketAds = mapper.selectByExample(example);
        sqlSession.close();
        return marketAds;
    }

    @Override
    public MarketAd update(MarketAd marketAd) {
        //todo marketAd根据参数情况判断是否执行操作

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        marketAd.setUpdateTime(new Date());
        mapper.updateByPrimaryKey(marketAd);
        sqlSession.commit();
        sqlSession.close();
        return marketAd;
    }

    @Override
    public MarketAd create(MarketAd marketAd) {
        //todo marketAd根据参数情况判断是否执行操作
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        Date now = new Date();
        marketAd.setAddTime(now);
        marketAd.setUpdateTime(now);
        mapper.insertSelective(marketAd);
        sqlSession.commit();
        sqlSession.close();
        return marketAd;
    }

    @Override
    public int delete(MarketAd marketAd) {
        //todo marketAd根据参数情况判断是否执行操作
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAdMapper mapper = sqlSession.getMapper(MarketAdMapper.class);
        int row = mapper.deleteByPrimaryKey(marketAd.getId());
        sqlSession.commit();
        sqlSession.close();
        return row;
    }
}
